<template>
  <div class="box">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h3 style="display: inline">样例-{{ sampleId + 1 }}：</h3>
          <el-button class="button" type="primary" style="float:right;" round
                     @click="onClose">
            关闭
          </el-button>
        </div>
      </template>
      <div class="text-item" v-html="prompt"/>
    </el-card>
    <generate-parameter-setter ref="generateParameterSetter" :editable="false"/>
    <h3>分辨真实文段：</h3>
    <el-row :gutter="20" v-loading="loading"
            element-loading-text="模型生成中">
      <el-col :span="12" v-for="i in [0, 1]" :key="'wiki-generate-task-card-' + cardIndex + '-choice-' + i">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <h4 style="display: inline">文段{{ i + 1 }}：</h4>
            </div>
          </template>
          <div class="text-item" v-html="text[i]"/>
          <el-divider/>
          <div style="text-align: center">
            <!--suppress HtmlUnknownTag -->
            <transition name="el-zoom-in-center">
              <el-button round
                         v-show="chooseButtonShow[i]"
                         :type="chooseButtonType[i]"
                         :icon="chooseButtonIcon[i]"
                         @click="onMakeChoice({index: i})"
              >{{ chooseButtonText[i] }}
              </el-button>
            </transition>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {ElMessage} from "element-plus";
import GenerateParameterSetter from "./GenerateParameterSetter.vue";

export default {
  name: "WikiGenerateTaskCard",
  components: {
    GenerateParameterSetter
  },
  data() {
    return {
      makeChoice: false,
      loading: true,
      text: [this.prompt, this.prompt],
      chooseButtonText: ['这是真实的', '这是真实的'],
      chooseButtonIcon: ['', ''],
      chooseButtonType: ['primary', 'primary'],
      chooseButtonShow: [true, true],
      trueIndex: -1,
    }
  },
  props: {
    sampleId: Number,
    prompt: String,
    cardIndex: Number,
    maxLength: Number,
    temperature: Number,
    topK: Number,
    topP: Number
  },
  mounted() {
    let generateParameterSetter = this.$refs.generateParameterSetter
    generateParameterSetter.table.maxLength = this.maxLength
    generateParameterSetter.table.temperature = this.temperature
    generateParameterSetter.table.topK = this.topK
    generateParameterSetter.table.topP = this.topP


    this.trueIndex = Math.random() <= 0.5 ? 0 : 1
    this.axios.get('/generate', {
      params: {
        index: this.sampleId,
        max_length: this.maxLength,
        temperature: this.temperature,
        top_k: this.topK,
        top_p: this.topP,
      }
    }).then(response => {
      let fakeIndex = (this.trueIndex === 1) ? 0 : 1, generated = response.data.generated,
          original = response.data.original, toBeContinued = response.data.toBeContinued
      if (toBeContinued) {
        // 没有生成一个完整的句子
        generated += '。。。'
        let length = 2
        if (original.length > 20) {
          // 原始文段长度大于20，随机选取末尾5~10个词抹除, 然后加上省略号，否则选2个字
          length = Math.floor(Math.random() * 11) + 5
        }
        original = original.substr(0, original.length - length)
        original += '。。。'
      }

      // 防止两者长度差异过大：截取原始文本
      if (original.length - generated.length > 25) {
        let length = generated.length + Math.floor(Math.random() * 11) - 5
        original = original.substr(0, length) + '。。。'
        generated = generated.substr(0, generated.length - 5) + '。。。'
      }

      this.text[this.trueIndex] = this.formatHTMLString(original)
      this.text[fakeIndex] = this.formatHTMLString(generated)
      this.loading = false
    }).catch(err => {
      ElMessage('获取文本生成结果' + this.sampleId + '失败, 详情见控制台')
      console.log(err)
      this.loading = false
    })
  },
  methods: {
    onClose() {
      this.$emit('close')
    },
    onMakeChoice({index}) {
      if (this.makeChoice) {
        return
      }
      if (index === this.trueIndex) {
        this.chooseButtonIcon[index] = 'el-icon-check'
        this.chooseButtonType[index] = 'success'
      } else {
        this.chooseButtonIcon[index] = 'el-icon-close'
        this.chooseButtonType[index] = 'danger'
        this.chooseButtonText[index] = '这是生成的'
      }
      this.chooseButtonShow[(index === 1) ? 0 : 1] = false
      this.makeChoice = true
    },
    // todo: 转换为工具函数
    formatHTMLString(string) {
      // 回车
      string = string.replace(/\r\n/g, "<br>").replace(/\n/g, "<br>").replace(/\r/g, "<br>");
      return string
    },
  }
}
</script>

<style scoped>
.box {
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 20px 2px 6px rgba(0, 0, 0, .04);
  border-radius: 4px;
  padding: 5px 10px 10px 10px;
}

.card-header {
  text-align: left;
}

.text-item {
  text-align: left;
}
</style>